// 注意：mui框架屏蔽了onclick和href事件。
// 解决方法：绑定tab使用js跳转。
// 需要跳转请在a标签上设置url属性
mui(document).on('tap', 'body a', function (e) {
    const url = this.getAttribute('url');
    if (url) window.location.href = url;

})

function openSide(selector = '.lib-aside') {
    let aside = document.querySelector(selector);
    let inClass = 'slideInLeft', outClass = 'slideOutLeft';
    if (aside.classList.contains('lib-aside-down') || aside.classList.contains('aside-down')) {
        inClass = 'slideInUp', outClass = 'slideOutDown';
    }
    aside.style.display = 'block';
    aside.classList.remove(outClass);
    aside.classList.add(inClass);

}

function closeSide(selector = '.lib-aside') {
    let aside = document.querySelector(selector);
    let inClass = 'slideInLeft', outClass = 'slideOutLeft';
    if (aside.classList.contains('lib-aside-down') || aside.classList.contains('aside-down')) {
        inClass = 'slideInUp', outClass = 'slideOutDown';
    }
    aside.classList.remove(inClass);
    aside.classList.add(outClass);
}

window.onload = function () {

    // 后退一页功能
    mui(document).on('tap', '.go-back', function () {
        history.back();
    })
    // 点击复制功能绑定
    if (window.ClipboardJS) {
        // 需要引用 clipboard.min.js
        let clipboard = new ClipboardJS('.copy');
        clipboard.on('success', function (e) {
            if (window.mui) {
                mui.toast('复制成功')
            } else {
                console.log('复制成功')
            }
            e.clearSelection();
        });

    }

    // 图片（选择）上传
    mui(document).on('change', ".file-upload > input[type='file']", function (e) {
        const file = e.target.files[0];//获取到当前文件对象
        let URL = window.URL || window.webkitURL;
        let imgUrl = URL.createObjectURL(file);
        let hasImage = false;
        e.target.parentElement.childNodes.forEach(function (item) {
            if (item.nodeName === 'IMG') {
                item.src = imgUrl;
                hasImage = true;
            }
        });
        if (!hasImage) {
            let IMG = new Image();
            IMG.src = imgUrl;
            e.target.parentElement.prepend(IMG);
        }

    });


};
let timer = null;

function sendCodeTiming(dom, interval = 60) {
    if (typeof dom === 'string') {
        dom = document.querySelector(dom);
    }
    if (!dom) {
        return;
    }
    dom.disabled = true;
    const timing = function (dom, interval, defaultText) {
        interval--;
        dom.innerHTML = interval + ' s';
        if (dom && interval > 0) {
            timer = setTimeout(function () {
                timing(dom, interval, defaultText);
            }, 1000);
        } else {
            dom.innerHTML = defaultText;
            dom.disabled = false;
        }

    };
    if (timer) {
        clearInterval(timer);
    }
    timing(dom, interval, dom.innerText);

}

/**
 * 表单提交
 * @param data 数据或表单选择器（例：#form、.form、{title:'',name:''}）
 * @param url  请求地址 data项为表单选择器时如果省略则 去 form.action
 * @param validatorCallback 字段验证函数：true:验证通过，string:提示信息
 * @param callback
 * @param redirect
 * @private
 */
function __submit(data, url, validatorCallback, callback, redirect = true) {
    if (!data) {
        mui.toast('表单数据不存在');
        return;
    }
    if (typeof data === 'string') {
        // 传入一个表单ID的选择器
        let form = document.querySelector(data);
        if (!form) {
            mui.toast('表单不存在');
            return;
        }

        let formData = new FormData();
        let validResult = true;

        Array.prototype.forEach.call(form, function (item) {
            // 验证不通过
            if (validResult !== true) return;

            if (item.name) {
                let value;
                if (item.type === 'checkbox' || item.type === 'radio') {
                    if (item.checked) value = item.value;
                } else if (item.type === 'file') {
                    value = item.files[0];
                } else {
                    value = item.value;
                }

                if (typeof value !== 'undefined') {
                    if (typeof validatorCallback === 'function') {
                        validResult = validatorCallback(item.name, value);
                        // 验证不通过
                        if (validResult !== true) return;

                    }
                    formData.append(item.name, value);
                }
            }

        });
        if (validResult !== true) {
            let validMessage = typeof validResult === 'string' && validResult.length > 0 ? validResult : '表单填写不正确';
            mui.toast(validMessage);
            return;
        }
        url = url || form.action || window.location.href;
        mui.ajax(url, {
            data: formData,
            type: 'post',
            dataType: 'json',
            processData: false,
            contentType: false,
            success(res) {
                __ajaxCallback(res, callback, redirect)
            }
        })

    } else {
        __post(url, data, callback, redirect)
    }

}

/**
 * res={
 *     status:true,
 *     data:{},
 *     url:'新的跳转地址，如果不为空则1.5s',
 *     message:'提示信息，如果不为空则显示提示'
 * }
 * ajax post操作
 * @param url 提交地址
 * @param data 提交数据
 * @param callback 结果处理函数（可选）
 * @param redirect 如果服务器返回跳转地址，是否进行跳转操作
 * @private
 */
function __post(url, data = {}, callback, redirect = true) {
    mui.post(url, data, function (res) {
            __ajaxCallback(res, callback, redirect)
        },
        'json'
    );
}

/**
 * res={
 *     status:true,
 *     data:{},
 *     url:'新的跳转地址，如果不为空则1.5s',
 *     message:'提示信息，如果不为空则显示提示'
 * }
 * ajax get操作
 * @param url 提交地址
 * @param data 提交数据
 * @param callback 结果处理函数（可选）
 * @param redirect 如果服务器返回跳转地址，是否进行跳转操作
 * @private
 */
function __get(url, data = {}, callback, redirect = true) {
    mui.get(url, data, function (res) {
            __ajaxCallback(res, callback, redirect)
        },
        'json'
    );
}

function __ajaxCallback(res, callback, redirect) {
    if (res.message && res.message.length) {
        mui.toast(res.message)
    }
    // 用户自定义处理操作
    if (typeof callback === 'function') {
        callback(res);
    }
    // 是否执行后续的跳转操作
    if (!redirect) return;
    // 1.5 秒后跳转
    let redirectUrl = res.url;
    if (redirectUrl && redirectUrl.length) {
        setTimeout(function () {
            window.location.href = redirectUrl;
        }, 1500)
    }
}


/**
 * 数字输入框
 * varstion 1.0.1
 * by Houfeng
 * Houfeng@DCloud.io
 */

(function ($) {

    var touchSupport = ('ontouchstart' in document);
    var tapEventName = touchSupport ? 'tap' : 'click';
    var changeEventName = 'change';
    var holderClassName = 'mui-numbox';
    var plusClassName = 'mui-numbox-btn-plus';
    var minusClassName = 'mui-numbox-btn-minus';
    var inputClassName = 'mui-numbox-input';


    var Numbox = $.Numbox = $.Class.extend({
        /**
         * 构造函数
         **/
        init: function (holder, options) {
            var self = this;
            if (!holder) {
                throw "构造 numbox 时缺少容器元素";
            }
            self.holder = holder;
            options = options || {};
            options.step = parseFloat(options.step || 1);
            self.options = options;
            self.input = $.qsa('.' + inputClassName, self.holder)[0];
            self.plus = $.qsa('.' + plusClassName, self.holder)[0];
            self.minus = $.qsa('.' + minusClassName, self.holder)[0];
            self.checkValue();
            self.initEvent();
        },
        /**
         * 初始化事件绑定
         **/
        initEvent: function () {
            var self = this;
            self.plus.addEventListener(tapEventName, function (event) {
                var val = floatAdd(parseFloat(self.input.value), self.options.step);
                self.input.value = val.toString();
                $.trigger(self.input, changeEventName, null);
            });
            self.minus.addEventListener(tapEventName, function (event) {
                var val = floatSub(parseFloat(self.input.value), self.options.step);
                self.input.value = val.toString();
                $.trigger(self.input, changeEventName, null);
            });
            self.input.addEventListener(changeEventName, function (event) {
                self.checkValue();
                var val = parseFloat(self.input.value);
                //触发顶层容器
                $.trigger(self.holder, changeEventName, {
                    value: val
                });
            });
        },
        /**
         * 获取当前值
         **/
        getValue: function () {
            var self = this;
            return parseFloat(self.input.value);
        },
        /**
         * 验证当前值是法合法
         **/
        checkValue: function () {
            var self = this;
            var val = self.input.value;
            if (val == null || val == '' || isNaN(val)) {
                self.input.value = self.options.min || 0;
                self.minus.disabled = self.options.min != null;
            } else {
                var val = parseFloat(val);
                if (self.options.max != null && !isNaN(self.options.max) && val >= parseFloat(self.options.max)) {
                    val = self.options.max;
                    self.plus.disabled = true;
                } else {
                    self.plus.disabled = false;
                }
                if (self.options.min != null && !isNaN(self.options.min) && val <= parseFloat(self.options.min)) {
                    val = self.options.min;
                    self.minus.disabled = true;
                } else {
                    self.minus.disabled = false;
                }
                self.input.value = val;
            }
        },
        /**
         * 更新选项
         **/
        setOption: function (name, value) {
            var self = this;
            self.options[name] = value;
        }
    });

    $.fn.numbox = function (options) {
        var instanceArray = [];
        //遍历选择的元素
        this.each(function (i, element) {
            if (element.numbox) return;
            if (options) {
                element.numbox = new Numbox(element, options);
            } else {
                var optionsText = element.getAttribute('data-numbox-options');
                var options = optionsText ? JSON.parse(optionsText) : {};
                options.step = element.getAttribute('data-numbox-step') || options.step;
                options.min = element.getAttribute('data-numbox-min') || options.min;
                options.max = element.getAttribute('data-numbox-max') || options.max;
                element.numbox = new Numbox(element, options);
            }
        });
        return this[0] ? this[0].numbox : null;
    }

    //自动处理 class='mui-locker' 的 dom
    $.ready(function () {
        $('.' + holderClassName).numbox();
    });

}(mui));


//乘
function floatMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}


//除
function floatDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try {
        t1 = arg1.toString().split(".")[1].length
    } catch (e) {
    }
    try {
        t2 = arg2.toString().split(".")[1].length
    } catch (e) {
    }

    r1 = Number(arg1.toString().replace(".", ""));

    r2 = Number(arg2.toString().replace(".", ""));
    return (r1 / r2) * Math.pow(10, t2 - t1);
}

//加
function floatAdd(arg1, arg2) {
    var r1, r2, m;
    try {
        r1 = arg1.toString().split(".")[1].length
    } catch (e) {
        r1 = 0
    }
    try {
        r2 = arg2.toString().split(".")[1].length
    } catch (e) {
        r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}

//减
function floatSub(arg1, arg2) {
    var r1, r2, m, n;
    try {
        r1 = arg1.toString().split(".")[1].length
    } catch (e) {
        r1 = 0
    }
    try {
        r2 = arg2.toString().split(".")[1].length
    } catch (e) {
        r2 = 0
    }
    m = Math.pow(10, Math.max(r1, r2));
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}